﻿# -*-coding: UTF-8 -*-
from PyQt5.QtCore import QTimer, Qt

import Globals
from CloverLauncher.LaunchActionType import LaunchActionType


class Launcher:
	LAUNCHER_ACTION_CLS = {}

	def __init__(self):
		self.launch_timer = None
		self.current_action = None
		self.launch_actions = []
		self.current_action_index = 0
		self.launch_timer = QTimer()
		self.launch_timer.setTimerType(Qt.PreciseTimer)
		self.launch_finish_callback = None

	def start(self, on_start, on_finished):
		self.launch_finish_callback = on_finished
		self.launch_actions = self.create_launch_actions()
		self.launch_timer.timeout.connect(self.on_exec_launch_action)
		self.launch_timer.start(1)
		self.current_action_index = 0
		self.current_action = self.launch_actions[self.current_action_index]
		self.current_action.start()
		on_start and on_start()

	def destroy(self):
		self.launch_timer.stop()
		self.current_action_index = 0
		self.current_action = None

	def on_exec_launch_action(self):
		if not self.current_action:
			self.launch_timer.stop()
			return
		if not self.current_action.is_finished():
			return
		self.current_action.stop()
		self.current_action_index += 1
		if self.current_action_index >= len(self.launch_actions):
			self.current_action = None
			self.launch_timer.stop()
			self.launch_finish_callback and self.launch_finish_callback()
			return

		self.current_action = self.launch_actions[self.current_action_index]
		self.current_action.start()

	def get_launch_progress(self):
		"""获取启动进度信息"""
		total_actions = len(self.launch_actions)
		current_action_progress = self.current_action.get_progress()
		progress_percent = (current_action_progress / (total_actions * 100)) * 100
		return progress_percent

	def get_launch_progress_description(self):
		action_desc = self.current_action.get_description()
		return action_desc

	def get_action_desc(self):
		progress, desc = self.get_launch_progress()
		return f"{desc} ({progress:.1f}%)"

	@classmethod
	def create_launch_actions(cls):
		result = []
		for action_type in LaunchActionType.ALL:
			action = cls.create_launch_action(action_type)
			if action:
				result.append(action)
		return result

	@classmethod
	def register_launch_action_cls(cls, action_type, action_cls):
		cls.LAUNCHER_ACTION_CLS[action_type] = action_cls

	@classmethod
	def create_launch_action(cls, action_type):
		if action_type not in cls.LAUNCHER_ACTION_CLS:
			return None
		action_cls = cls.LAUNCHER_ACTION_CLS[action_type]
		return action_cls(action_type)


def register_launch_action(action_type):
	def action_cls(cls):
		Launcher.register_launch_action_cls(action_type, cls)
		return cls

	return action_cls
